package cn.itcast.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author dejawu
 * @Title: LoginFilter
 * @Description: 全局过滤器，实现登录功能
 * @date 2021/1/3
 */
@Component
@Order(10)   //越小越优先执行   建议  10 20 30 40 50  方便中间插入
public class LoginFilter implements GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、得到 request 和 response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2、获取请求参数
        String token = request.getQueryParams().getFirst("token");
        //2.1、请求参数中没有token   直接拦截
        if (StringUtils.isBlank(token)){
            //设置状态码
            response.setStatusCode(HttpStatus.OK);    //HttpStatus  web中所有的状态码
            //响应给前端
            return response.setComplete();
        }
        //2.2、  有token  判断token
        if (!"admin".equals(token)){
            //设置状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);    //HttpStatus  web中所有的状态码
            //响应给前端
            return response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }
}